package com.ruoyi.generator.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.generator.service.IGenTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 北京XXX信息技术有限公司-版权所有
 * @Package com.ruoyi.generator.controller
 * @ClassName DiyController
 * @Description (接口代码生成)
 * @author yuanpingfang
 * @date 2020-12-29 15:45
 * @version 1.0
 */
@RestController
@RequestMapping("/tool/diy")
public class DiyController extends BaseController {

    @Autowired
    private IGenTableService genTableService;
    /**
     * 生成代码（下载方式）
     */
    @PreAuthorize("@ss.hasPermi('tool:diy:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @PostMapping("/download")
    public void download(HttpServletResponse response, @RequestBody Map<String, Object> requestMap) throws IOException
    {
        byte[] data = genTableService.downloadCode(requestMap);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
